<template>
  <el-dialog :model-value="visible" :close-on-click-modal="false"
             :title="getTitle()" class="crm-ralative" width="60%" append-to-body @close="closeView">
    <div class="cr-contianer">
      <div style="position: relative;">
        <div v-if="crmType == '' && !commonConfig.isCommon" class="cr-body-side">
          <div v-for="(item, index) in leftSides" :key="index"
               :class="leftType===item.type? 'side-item-select' : 'side-item-default'"
               class="side-item"
               @click="sideClick(item)">{{ item.name }}
            <span v-if="item.num > 0" class="side-item__num">{{ `(${item.num})` }}</span>
          </div>
        </div>
        <div v-if="commonConfig.isCommon">
          <template v-for="(item, index) in leftSides" :key="index">
            <crm-relative-table v-if="item.loaded" v-show="item.type == leftType"
                                ref="moduleTable"
                                :props="commonConfig"
                                :selected-data="currentSelectedData[item.type]"
                                @selection-change="selectionChange($event, item)"/>
          </template>
        </div>
        <div v-else :style="{ 'padding-left': crmType == '' ? '150px' : '0'}">
          <template v-for="(item, index) in leftSides" :key="index">
            <component v-if="item.loaded" v-show="item.type == leftType"
                       ref="moduleTable"
                       :props="componentConfig"
                       :selected-data="currentSelectedData[item.type]"
                       :is="getComponentsName(item.type)"
                       @selection-change="selectionChange"/>
          </template>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button @click="closeView">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {objDeepCopy} from '/src/utils/index.js'
import merge from '/src/utils/merge.js'
import {ref, watch, getCurrentInstance, nextTick, computed, onMounted} from "vue"


import CustomerIndex from '/src/views/crm/customer/index.vue'
import ContactsIndex from '/src/views/crm/contract/index.vue'
import BusinessIndex from '/src/views/crm/business/index.vue'
import ContractIndex from '/src/views/crm/contract/index.vue'
import LeadsIndex from '/src/views/crm/leads/AllIndex.vue'
import ProductIndex from '/src/views/crm/product/index.vue'
import CrmRelativeTable from './CrmRelativeTable.vue'

// 通用配置 含 CrmRelativeTable 声明的信息
const DefaultCommon = {
  isCommon: false,
  type: '',
  name: ''
}

// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus

defineOptions({
  name: 'CrmRelatieve', // 相关
})


const props = defineProps({
  visible: Boolean,
  /** 多选框 只能选一个 */
  radio: {
    type: Boolean,
    default: true
  },
  acceptEmail: {
    type: String,
    default: ''
  },
  /** 没有值就是全部类型 有值就是当个类型 */
  crmType: {
    type: String,
    default: ''
  },
  /** 需要展示哪些类型 默认关键字数组 */
  showTypes: {
    type: Array,
    default: () => {
      return [
        'customer',
        'contacts',
        'leads',
        'business',
        'contract',
        'product'
      ]
    }
  },
  /** 已选信息 */
  selectedData: {
    type: Object,
    default: () => {
      return {}
    }
  },
  /**
   * default 默认  condition 固定条件筛选 moduleType 下的
   * relative: 相关 添加
   */
  action: {
    type: Object,
    default: () => {
      return {
        type: 'default',
        data: {}
      }
    }
  }
})

const emits = defineEmits(['close', 'update:visible', 'changeCheckout'])

const leftType = ref('')
const leftSides = ref([])
/** 各类型选择的值 */
const currentSelectedData = ref({})


provide('elForm', '')
provide('elFormItem', '')


/**
 * 通用配置
 */
const commonConfig = computed(() => {
  return merge({...DefaultCommon}, props.action || {})
})

/**
 * 模块配置
 */
const componentConfig = computed(() => {
  const tableHeight = document.documentElement.clientHeight - 370

  const params = {}
  if (props.action && props.action.type === 'condition') {
    params[props.action.data.moduleType + 'Id'] = props.action.data[
    props.action.data.moduleType + 'Id'
        ]
    if (props.action.data.params) {
      for (const field in props.action.data.params) {
        params[field] = props.action.data.params[field]
      }
    }
  }
  return {
    isSelect: true,
    showModuleName: false,
    selectionHandle: false,
    radio: props.radio,
    params,
    tableHeight
  }
})

watch(() => props.visible, (val) => {
      console.log("val", val)
      if (val) {
        nextTick(() => {
          // getCurrentMainTable().getMainTable().doLayout()
        })
      }
    },
    {
      // 如果想在侦听器回调中能访问被 Vue 更新之后的 DOM，你需要指明 flush: 'post' 选项：
      flush: "post"
    })

watch(() => props.selectedData, (data) => {
  handleCurrentSelectData(data)
})


onMounted(() => {
  // 获取传值
  handleCurrentSelectData(props.selectedData)
})


/**
 * 目前选择值
 */
function handleCurrentSelectData(data) {
  console.log("handleCurrentSelectData", data)
  if (commonConfig.value.isCommon) {
    const tempData = {}
    tempData[commonConfig.value.type] = []
    currentSelectedData.value = tempData
  } else {
    if (data && Object.keys(data).length) {
      currentSelectedData.value = objDeepCopy(data)
    } else {
      const tempData = {}
      if (props.crmType) {
        tempData[props.crmType] = []
        currentSelectedData.value = tempData
      } else {
        for (let index = 0; index < props.showTypes.length; index++) {
          const key = props.showTypes[index]
          tempData[key] = []
        }
        currentSelectedData.value = tempData
      }
    }
  }

  // 初始化
  if (commonConfig.value.isCommon) {
    leftSides.value.push({
      name: commonConfig.value.name,
      isCommon: true, // 是统一效果
      loaded: true,
      num: 0,
      type: commonConfig.value.type
    })
    leftType.value = commonConfig.value.type
  } else {
    if (leftSides.value.length === 0) {
      const leftItems = getLeftItems()
      if (props.crmType) {
        const leftItem = leftItems[props.crmType]
        leftItem.loaded = true
        leftSides.value.push(leftItem)
        leftType.value = props.crmType
      } else {
        for (let index = 0; index < props.showTypes.length; index++) {
          const leftItem = leftItems[props.showTypes[index]]
          const leftData = currentSelectedData.value[leftItem.type]
          leftItem.num = leftData ? leftData.length : 0
          leftSides.value.push(leftItem)
        }

        if (leftSides.value.length > 0) {
          const leftItem = leftSides.value[0]
          leftItem.loaded = true
          leftType.value = leftItem.type
        }
      }
    } else {
      // 更新多tabs 下数据
      if (!props.crmType) {
        for (let index = 0; index < leftSides.value.length; index++) {
          const leftItem = leftSides.value[index]
          const leftData = currentSelectedData.value[leftItem.type]
          leftItem.num = leftData ? leftData.length : 0
        }
      }
    }
  }
}

/**
 * 刷新列表
 */
function refreshList() {
  cxt.refs['crm' + props.crmType][0].refreshList()
}

/**
 * 侧边点击
 */
function sideClick(item) {
  leftType.value = item.type
  item.loaded = true
}

/**
 * 关闭操作
 */
function closeView() {
  emits('close')
  emits('update:visible', false)
}

/**
 * 勾选change
 */
function selectionChange(data, item) {
  console.log("selectionChange", data, item)
  // item.num = data.length
  currentSelectedData.value[leftType.value] = data
  console.log("selectionChange", currentSelectedData, item)
}

/**
 * 确定选择
 */
function confirmClick() {
  // 如果是单类型 在这里数据赋值
  console.log("props", props)
  console.log("props", currentSelectedData)
  console.log("props", leftType)
  console.log("props", getCurrentMainTable())
  // if (props.crmType) {
  //   currentSelectedData.value[leftType.value] = getCurrentMainTable().selectionList
  // }

  if (props.crmType) {
    if (props.acceptEmail == 'receive') {
      emits('changeCheckout', {data: currentSelectedData.value[props.crmType], type: 'receive'})
    } else if (props.acceptEmail == 'sent') {
      emits('changeCheckout', {data: currentSelectedData.value[props.crmType], type: 'sent'})
    } else {
      // 以单类型传值
      emits('changeCheckout', {
        data: currentSelectedData.value[props.crmType]
            ? currentSelectedData.value[props.crmType]
            : []
      })
    }
  } else {
    emits('changeCheckout', {data: currentSelectedData.value})
  }

  nextTick(() => {
    closeView()
  })
}

/**
 * 获取当前主列表对象
 */
function getCurrentMainTable() {
  console.log("cxt", cxt)
  console.log("cxt", cxt.refs)
  console.log("cxt", leftType)
  const list = cxt.refs.moduleTable
  console.log("cxt", list)
  return list

  // 到这里了
  // const opstionsName = getComponentsName(leftType.value)
  // console.log("opstionsName",opstionsName)
  // console.log("opstionsName",opstionsName.setup)
  // console.log("list",list)
  // return list.find(item => item.$options && item.$options.name === opstionsName)
}

/**
 * 根据类型获取标题展示名称
 */
function getTitle() {
  if (commonConfig.value.isCommon) {
    return commonConfig.value.name
  }
  if (props.crmType == 'leads') {
    return '关联线索模块'
  } else if (props.crmType == 'customer') {
    return '关联客户模块'
  } else if (props.crmType == 'contacts') {
    return '关联联系人模块'
  } else if (props.crmType == 'business') {
    return '关联商机模块'
  } else if (props.crmType == 'product') {
    return '关联产品模块'
  } else if (props.crmType == 'contract') {
    return '关联合同模块'
  } else {
    return '关联相关信息'
  }
}

/**
 * 获取组件名称
 */
function getComponentsName(type) {
  if (type === 'customer') {
    return CustomerIndex
  } else if (type === 'contacts') {
    return ContactsIndex
  } else if (type === 'leads') {
    return LeadsIndex
  } else if (type === 'business') {
    return BusinessIndex
  } else if (type === 'contract') {
    return ContractIndex
  } else if (type === 'product') {
    return ProductIndex
  } else {
    return CrmRelativeTable
  }
}

/**
 * 设置勾选值
 */
const setSelections = (data) => {
  console.log("setSelections", data)
  getCurrentMainTable().setSelections(data)
}

defineExpose({setSelections})

/**
 * 切换某一行的选中状态
 */
function toggleRowSelection(rowKey, rowId, selected) {
  getCurrentMainTable().toggleRowSelection(rowKey, rowId, selected)
}

/**
 * 获取左侧菜单信息
 */
function getLeftItems() {
  return {
    customer: {
      name: '客户',
      loaded: false,
      num: 0,
      type: 'customer'
    },
    contacts: {
      name: '联系人',
      loaded: false,
      num: 0,
      type: 'contacts'
    },
    leads: {
      name: '线索',
      loaded: false,
      num: 0,
      type: 'leads'
    },
    business: {
      name: '商机',
      loaded: false,
      num: 0,
      type: 'business'
    },
    contract: {
      name: '合同',
      loaded: false,
      num: 0,
      type: 'contract'
    },
    product: {
      name: '产品',
      loaded: false,
      num: 0,
      type: 'product'
    }
  }
}


</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.cr-contianer {
  position: relative;
  height: 100%;
}

.dialog-footer {
  text-align: right;
  margin-top: 10px;
  margin-right: 10px;
}

.cr-body-side {
  flex-shrink: 0;
  z-index: 3;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 150px;
  font-size: 12px;
  background-color: white;
  height: 100%;
  border-right: 1px solid #e6e6e6;

  .side-item {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    font-size: 14px;
    color: #333;
    cursor: pointer;

    &__num {
      color: #666;
      font-size: 12px;
      position: absolute;
      top: 0;
      right: 5px;
    }
  }

  .side-item::before {
    content: ' ';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 2px;
  }
}

.side-item-default {
  color: #333;
}

.side-item-select {
  background-color: $xr--background-color-base;
}

.side-item-select::before {
  background-color: $xr-color-primary;
}

.el-dialog__wrapper {
  :deep(.el-dialog) {
    margin-top: 60px !important;
    height: calc(100% - 110px);
  }

  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100% - 100px);
  }
}
</style>
